/**
 * Projects 模块 API
 * 项目管理相关接口
 */

import { request, type ApiResponse, type RequestParamValue } from "../request";

// ============ 类型定义 ============

/**
 * 项目状态枚举
 */
export type ProjectStatus =
	| "INACTIVE"
	| "ACTIVE_HEALTHY"
	| "ACTIVE_UNHEALTHY"
	| "COMING_UP"
	| "UNKNOWN"
	| "GOING_DOWN"
	| "INIT_FAILED"
	| "REMOVED"
	| "RESTORING"
	| "UPGRADING"
	| "PAUSING"
	| "RESTORE_FAILED"
	| "RESTARTING"
	| "PAUSE_FAILED"
	| "RESIZING";

/**
 * 项目数据库信息
 */
export type ProjectDatabase = {
	host: string;
	version: string;
	postgres_engine: string;
	release_channel: string;
};

/**
 * 项目信息（带数据库）
 */
export type Project = {
	id: string;
	ref: string;
	organization_id: string;
	organization_slug: string;
	name: string;
	region: string;
	created_at: string;
	status: ProjectStatus;
	database: ProjectDatabase | null;
};

/**
 * 创建项目请求
 */
export type CreateProjectBody = {
	db_pass: string;
	name: string;
	organization_id: string | null;
	organization_slug: string | null;
	plan: "free" | "pro" | "team" | "enterprise" | null;
	region: string | null;
	kps_enabled: boolean | null;
	desired_instance_size: string | null;
	template_url: string | null;
	release_channel: string | null;
	postgres_engine: string | null;
};

/**
 * 智能区域组信息
 */
export type SmartGroupRegion = {
	name: string;
	code: string;
	type: "smartGroup";
};

/**
 * 具体区域信息
 */
export type SpecificRegion = {
	name: string;
	code: string;
	type: "specific";
	provider: string;
	status: string;
};

/**
 * 可用区域信息
 */
export type RegionsInfo = {
	recommendations: {
		smartGroup: SmartGroupRegion | null;
		specific: SpecificRegion[] | null;
	};
	all: {
		smartGroup: SmartGroupRegion[] | null;
		specific: SpecificRegion[] | null;
	};
};

/**
 * 网络封禁地址项
 */
export type NetworkBanAddressItem = {
	banned_address: string;
	identifier: string;
	type: string;
};

/**
 * 网络封禁信息
 */
export type NetworkBan = {
	banned_ipv4_addresses: string[];
};

/**
 * 网络封禁详情
 */
export type NetworkBanEnriched = {
	banned_ipv4_addresses: NetworkBanAddressItem[];
};

/**
 * 网络 CIDR 配置
 */
export type NetworkCidrConfig = {
	dbAllowedCidrs: string[] | null;
	dbAllowedCidrsV6: string[] | null;
};

/**
 * 网络限制配置
 */
export type NetworkRestrictions = {
	entitlement: "disallowed" | "allowed";
	config: NetworkCidrConfig;
	old_config: NetworkCidrConfig | null;
	status: "stored" | "applied";
	updated_at: string | null;
	applied_at: string | null;
};

/**
 * 更新网络限制请求
 */
export type UpdateNetworkRestrictionsBody = {
	add: NetworkCidrConfig | null;
	remove: NetworkCidrConfig | null;
};

/**
 * 移除网络封禁请求
 */
export type RemoveNetworkBanBody = {
	ipv4_addresses: string[] | null;
	requester_ip: boolean | null;
	identifier: string | null;
};

/**
 * 服务健康状态类型
 */
export type HealthServiceName = "auth" | "db" | "db_postgres_user" | "pooler" | "realtime" | "rest" | "storage" | "pg_bouncer";

/**
 * 服务健康状态枚举
 */
export type HealthStatus = "COMING_UP" | "ACTIVE_HEALTHY" | "UNHEALTHY";

/**
 * 服务信息
 */
export type ServiceInfo = {
	name: string;
	version: string;
	description: string;
};

/**
 * 服务健康响应项
 */
export type ServiceHealthItem = {
	name: HealthServiceName;
	healthy: boolean;
	status: HealthStatus;
	info: ServiceInfo | null;
	error: string | null;
};

// ============ API 方法 ============

/**
 * 获取所有项目列表
 */
export function listProjects(): Promise<ApiResponse<Project[]>> {
	return request.get<Project[]>("/v1/projects");
}

/**
 * 获取单个项目详情
 */
export function getProject(ref: string): Promise<ApiResponse<Project>> {
	return request.get<Project>(`/v1/projects/${ref}`);
}

/**
 * 获取项目服务健康状态
 */
export function getProjectHealth(
	ref: string,
	services: HealthServiceName[],
	timeout_ms: number | null = null
): Promise<ApiResponse<ServiceHealthItem[]>> {
	const params: Record<string, RequestParamValue> = {
		services: services.join(",")
	};
	if (timeout_ms != null) {
		params["timeout_ms"] = timeout_ms;
	}
	return request.get<ServiceHealthItem[]>(`/v1/projects/${ref}/health`, params);
}

/**
 * 创建项目
 */
export function createProject(data: CreateProjectBody): Promise<ApiResponse<Project>> {
	return request.post<Project>("/v1/projects", data);
}

/**
 * 获取可用区域
 */
export function getAvailableRegions(params: {
	organization_slug: string;
	continent?: "NA" | "SA" | "EU" | "AF" | "AS" | "OC" | "AN";
	desired_instance_size?: string;
}): Promise<ApiResponse<RegionsInfo>> {
	return request.get<RegionsInfo>("/v1/projects/available-regions", params as Record<string, RequestParamValue>);
}

/**
 * 获取项目网络封禁列表
 */
export function getNetworkBans(ref: string): Promise<ApiResponse<NetworkBan>> {
	return request.post<NetworkBan>(`/v1/projects/${ref}/network-bans/retrieve`);
}

/**
 * 获取项目网络封禁详情
 */
export function getNetworkBansEnriched(
	ref: string
): Promise<ApiResponse<NetworkBanEnriched>> {
	return request.post<NetworkBanEnriched>(
		`/v1/projects/${ref}/network-bans/retrieve/enriched`
	);
}

/**
 * 移除网络封禁
 */
export function removeNetworkBans(
	ref: string,
	data: RemoveNetworkBanBody
): Promise<ApiResponse<Record<string, never>>> {
	return request.delete<Record<string, never>>(
		`/v1/projects/${ref}/network-bans`,
		data
	);
}

/**
 * 获取网络限制配置
 */
export function getNetworkRestrictions(
	ref: string
): Promise<ApiResponse<NetworkRestrictions>> {
	return request.get<NetworkRestrictions>(`/v1/projects/${ref}/network-restrictions`);
}

/**
 * 更新网络限制配置
 */
export function updateNetworkRestrictions(
	ref: string,
	data: UpdateNetworkRestrictionsBody
): Promise<ApiResponse<NetworkRestrictions>> {
	return request.patch<NetworkRestrictions>(
		`/v1/projects/${ref}/network-restrictions`,
		data
	);
}

export default {
	listProjects,
	getProject,
	getProjectHealth,
	createProject,
	getAvailableRegions,
	getNetworkBans,
	getNetworkBansEnriched,
	removeNetworkBans,
	getNetworkRestrictions,
	updateNetworkRestrictions
};
